from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
import uuid
from Rufe.storage import ImageStorage


# 自定义Manager管理器
class UserProfileManager(BaseUserManager):
    def _create_user(self, username, password, phone, **kwargs):
        if not username:
            raise ValueError("请输入用户名！")
        if not password:
            raise ValueError("请输入密码！")
        if not phone:
            raise ValueError("请传入手机号码！")
        user = self.model(username=username, phone=phone, **kwargs)
        user.set_password(password)
        user.save()
        return user

    # 创建普通用户
    def create_user(self, username, password, phone, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user(username, password, phone, **kwargs)

    # 创建超级用户
    def create_superuser(self, username, password, phone, **kwargs):
        kwargs['is_superuser'] = True
        kwargs['is_staff'] = True
        return self._create_user(username, password, phone, **kwargs)

    class Meta:
        verbose_name = "UserProfileManager"


# class Groups(models.Model):
#     gid = models.AutoField(primary_key=True)
#     name = models.CharField(max_length=30, verbose_name="用户组名", unique=True)
#
#     def __str__(self):
#         return self.name
#
#     def user_list(self):
#         return ','.join([i.username for i in self.userprofile_set.all()])
#
#     class Meta:
#         db_table = "Groups"
#         verbose_name = 'Group'


# 自定义User
class UserProfile(AbstractBaseUser, PermissionsMixin):
    GENDER_CHOICE = (
        (u'M', u'Male'),
        (u'F', u'Female'),
    )
    uid = models.UUIDField(primary_key=True, auto_created=True,
                           default=uuid.uuid4, editable=False,
                           verbose_name=u'User uuid',
                           help_text="User uuid"
                           )
    username = models.CharField(max_length=15, verbose_name="用户名", unique=True)
    nickname = models.CharField(max_length=13, verbose_name="昵称", null=True, blank=True)
    birthday = models.DateField(verbose_name="生日", null=True, blank=True)
    gender = models.CharField(max_length=2, choices=GENDER_CHOICE, verbose_name="性别", null=True, blank=True)
    phone = models.CharField(max_length=11, unique=True, blank=True, verbose_name="手机号码")
    email = models.EmailField(verbose_name="邮箱", null=True, blank=True)
    photo = models.ImageField(upload_to="photo/user_picture/%Y/%m/%d", verbose_name="用户头像", null=True, blank=True,
                              storage=ImageStorage())
    address = models.CharField(max_length=100, null=True, blank=True, verbose_name="地址")
    card_id = models.CharField(max_length=30, verbose_name="身份证", null=True, blank=True)
    is_active = models.BooleanField(default=True, verbose_name="激活状态")
    is_staff = models.BooleanField(default=True, verbose_name="是否是员工")
    date_joined = models.DateTimeField(auto_now_add=True)
    mod_date = models.DateTimeField(auto_now=True)
    # 使用authenticate验证时使用的验证字段，可以换成其他字段，但验证字段必须是唯一的，即设置了unique=True
    USERNAME_FIELD = 'username'
    # 创建用户时必须填写的字段，除了该列表里的字段还包括password字段以及USERNAME_FIELD中的字段
    REQUIRED_FIELDS = ['phone']
    # 发送邮件时使用的字段
    EMAIL_FIELD = 'email'

    # 手动指定中间表，可以使用该through选项指定表示要使用的中间表的Django模型。
    # group = models.ManyToManyField(UserGroup, through='UserGroup', verbose_name="组", blank=True)

    # roles = models.ManyToManyField("Role", through='UserRole', verbose_name="角色", blank=True)
    # ————#DJANGO账号权限 开始————
    def has_perm(self, perm, obj=None):  # 权限#用户有一个特定的许可吗?
        return True

    def has_module_perms(self, app_label):  # 用户有权限查看应用名称吗？
        return True

    class Meta:
        db_table = "Users"
        verbose_name = 'User'
        ordering = ['-uid', ]

    def __str__(self):
        return '用户 -- ' + self.username

    objects = UserProfileManager()

    # def group_list(self):
    #     return ','.join([i.name for i in self.group.all()])


from datetime import datetime


class UserToken(models.Model):
    user = models.OneToOneField(to='UserProfile', unique=True, on_delete=models.DO_NOTHING)
    token = models.CharField(max_length=128, verbose_name="用户token")
    expiration_time = models.DateTimeField(default=datetime.now, verbose_name="过期时间")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        # managed = True
        db_table = 'Users_Token'
        verbose_name = "用户Token"

    def __str__(self):
        return self.token


# class UserGroup(models.Model):
#     """用户组(中间实体)"""
#     ugid = models.AutoField(primary_key=True)
#     user = models.ForeignKey('UserProfile', on_delete=models.PROTECT, db_column='uid', null=False)
#     group = models.ForeignKey('Groups', on_delete=models.PROTECT, db_column='gid', null=False)
#
#     class Meta:
#         db_table = 'users_groups'
#         unique_together = (('user', 'group'),)


# class Role(models.Model):
#     rid = models.AutoField(primary_key=True, editable=False,
#                            verbose_name=u'Role uuid',
#                            help_text="Role uuid"
#                            )
#     name = models.CharField(max_length=32, unique=True, verbose_name="角色")
#     permissions = models.ManyToManyField("Permission", through='RolePermission', blank=True, verbose_name="URL授权")
#     desc = models.CharField(max_length=50, blank=True, null=True, verbose_name="描述")
#
#     class Meta:
#         db_table = "Role"
#
#     def __str__(self):
#         return self.name
#
#
# class UserRole(models.Model):
#     """用户角色(中间实体)"""
#     urid = models.AutoField(primary_key=True)
#     user = models.ForeignKey('UserProfile', on_delete=models.PROTECT, db_column='uid', null=False)
#     role = models.ForeignKey('Role', on_delete=models.PROTECT, db_column='rid', null=False)
#
#     class Meta:
#         db_table = 'tb_user_role'
#         unique_together = (('user', 'role'),)


# class Permission(models.Model):
#     pid = models.AutoField(primary_key=True, editable=False,
#                            verbose_name=u'Permission uuid',
#                            help_text="Permission uuid"
#                            )
#     title = models.CharField(max_length=32)
#     url = models.CharField(max_length=128)
#
#     class Meta:
#         db_table = "Permission"
#
#     def __str__(self):
#         return self.title
#
#
# class GroupPermission(models.Model):
#     """角色权限(中间实体)"""
#     gpid = models.AutoField(primary_key=True)
#     group = models.ForeignKey('Groups', on_delete=models.CASCADE, db_column='gid', null=False)
#     permission = models.ForeignKey('Permission', on_delete=models.CASCADE, db_column='pid', null=False)
#
#     class Meta:
#         db_table = 'users_user_permissions'
#         unique_together = (('group', 'permission'),)
